package com.soviet.boot.common.aspect;

import com.soviet.boot.common.base.ResultModel;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 *
 */
@Slf4j
@Component
@Aspect
public class UnionResultAspect {
    private static final String OBJECT_NAME = "java.lang.Object";

    @Pointcut("@within(com.soviet.boot.common.annotation.ResultAndLog) || " +
            "@annotation(com.soviet.boot.common.annotation.ResultAndLog)")
    public void result() {

    }

    @Around("result()")
    public Object convertResult(ProceedingJoinPoint pjp) throws Throwable {

        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();

        Signature signature = pjp.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        String returnName = methodSignature.getReturnType().getName();
        Object result = pjp.proceed();

        if (OBJECT_NAME.equals(returnName)) {
            result = new ResultModel<>(result);
        } else {
            log.warn("Return type must be Object type, {}.", returnName);
        }

        return result;
    }
}
